package io.coderyeah.org.controller;

import cn.hutool.core.bean.BeanUtil;
import io.coderyeah.basic.Result;
import io.coderyeah.org.domain.Department;
import io.coderyeah.org.domain.Employee;
import io.coderyeah.org.dto.EmpDTO;
import io.coderyeah.org.service.DepartmentService;
import io.coderyeah.org.service.EmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;


@RestController
@RequestMapping("/emp")
@Api("员工接口类")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private DepartmentService departmentService;


    @GetMapping
    public Result getAll() {
        return Result.success(employeeService.list());
    }


    @ApiOperation("分页查询部门列表")
    @PostMapping("/list")
    public Result list(@RequestBody EmpDTO empDTO) {
        return employeeService.getAll(empDTO);
    }

    @ApiOperation("根据店铺ID查询所有员工")
    @GetMapping("/list/{shopId}")
    public Result getEmpsByShopId(@PathVariable("shopId") Long shopId) {
        return employeeService.getEmpsByShopId(shopId);
    }

    /**
     * @param id 部门id
     * @return result
     */
    @ApiOperation("通过ID查询部门")
    @GetMapping("/{id}")
    public Result getById(@PathVariable("id") Long id) {
        return null;
    }

    @ApiOperation("添加/修改部门")
    @PostMapping("/saveOrUpdate")
    public Result saveOrUpdate(@RequestBody EmpDTO empDTO) {
        try {
            employeeService.saveOrModify(BeanUtil.copyProperties(empDTO, Employee.class));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
        return Result.success(null);
    }

    @ApiOperation("删除部门")
    @DeleteMapping("/del/{id}")
    public Result deleteById(@PathVariable("id") Long id) {
        try {
            employeeService.removeById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
        return Result.success("删除成功");
    }

    @ApiOperation("修改状态")
    @PostMapping("/editType")
    public Result editType(@RequestBody EmpDTO empDTO) {
        return employeeService.editType(empDTO);
    }

    @ApiOperation("获取所有部门")
    @PostMapping("/depts")
    public Result getDepts() {
        final List<Department> list = departmentService.list();
        return Result.success(list);
    }

    @ApiOperation("批量删除")
    @PatchMapping("/delByBatch")
    @Transactional
    public Result delByBatch(@RequestBody EmpDTO empDTO) {
        System.out.println(Arrays.toString(empDTO.getIds()));
        employeeService.removeByIds(Arrays.asList(empDTO.getIds()));
        return Result.success("批量删除成功");
    }
}
